package com.lcx.security.dao;



import com.lcx.security.entity.TaskEntity;
import com.lcx.security.service.impl.DefaultOutHandlerMethod;
import com.lcx.security.service.impl.TaskHandlerImpl;

import java.util.Collection;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * 任务信息持久层实现
 */
public class TaskDaoImpl{
	// 存放任务信息
	private static ConcurrentMap<String, TaskEntity> map =  new ConcurrentHashMap<>();

	public static TaskEntity query(String id) {
	return map.get(id);
}

	public static void delete(String id) {
		map.remove(id);
	}

	public TaskEntity get(String id) {
		return map.get(id);
	}


	public Collection<TaskEntity> getAll() {
		return map.values();
	}


	public int add(TaskEntity taskEntity) {
		String id = taskEntity.getId();
//		if (id == null ){
//			throw new RuntimeException("TaskEntity 的 id 不能为null");
//		}
		if (id != null && !map.containsKey(id)) {
			map.put(taskEntity.getId(), taskEntity);
			if(map.get(id)!=null)
			{
				return 1;
			}
		}else {
			TaskEntity oldTaskEntity = map.get(id);
			TaskHandlerImpl taskHandler = new TaskHandlerImpl(new DefaultOutHandlerMethod());
			taskHandler.stop(oldTaskEntity);
			map.put(taskEntity.getId(), taskEntity);
			if(map.get(id)!=null)
			{
				return 1;
			}
		}
		return 0;
	}


	public int remove(String id) {
		if(map.remove(id) != null){
			return 1;
		};
		return 0;
	}


	public int removeAll() {
		int size = map.size();
		try {
			map.clear();
		} catch (Exception e) {
			return 0;
		}
		return size;
	}


	public boolean isHave(String id) {
		return map.containsKey(id);
	}

}
